const Base = require('./base.js');

const request = require('request-promise');
const crypto = require('crypto');
const sha1 = require('node-sha1');
// const secret = ctx.config('secret'); //获取 secret 配置
function encryptSha1(data) {
  return crypto.createHash('sha1').update(data, 'utf8').digest('hex');
}
function createNonceStr(length = 16) {
    const buf = Buffer.alloc(10);
    return crypto.randomFillSync(buf).toString('hex');
  }
// const loginCode = //生成 authration header
module.exports = class extends Base {
  async readRedisAction () {
    // 15168325036
    const mobile = this.get('mobile')
    const key = 'dev_register_check_code_:' + mobile
    const value = await this.cache(key);
    this.success({key: value})
  }
  async smsAction() {
    const smscode = Math.floor(Math.random()*10000+1000);
    await this.cache('smscode', smscode);
    return this.success({ smscode }, '短信发送成功');
  }
  async isLoginAction() {
    return this.fail('未登录');
  }
  async getListAction() {
    this.success({
      list:[
        {id:1,name:'aaaa',title:'bbbb', content:'cccc',star:100,count:200},
        {id:1,name:'aaaa',title:'bbbb', content:'cccc',star:100,count:200},
        {id:1,name:'aaaa',title:'bbbb', content:'cccc',star:100,count:200},
        {id:1,name:'aaaa',title:'bbbb', content:'cccc',star:100,count:200}
      ],
      page: {
        pageNo: 1,
        pageSize: 5,
        totalCount: 3,
        totalPage: 1
      }
    });
  }
  async getCityAction () {
    const model = this.model('xr_city');
    const city = await model.field('name_cn,code,id,pid,level').where(`pid=1`).select();
    for (let item of city){
       item['children'] = await model.field('name_cn,code,id,pid,level').where(`pid=${item.id}`).select();
    }
    // city.forEach(async (item) => {
    //   item['children'] = await model.where(`pid=${item.id}`).find();
    // })
    this.success(city)
  }
  async getUserInfoAction () {
    
  }
  async imageCodeAction () {
    const imageCode = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAADUAAAAZCAIAAAAe6vFqAAAE5ElEQVRIicWWeVATdxTHHzcCFoqIhFChUcOttDShHBYHGQRLO5xVh9uCIDBoh4JUwWoRK8o9QCaDFaTB0WGklFYOUUSpUMgQUMAOCDShMALlUkxCOEL/WGYJy24IwkzfX9997/t777O7v9/OysUzmoAg9Jyah+tsEH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EU9wO8+ofzfL58zMzU/197KwMTm6O3dnE1VOEExMAIBwbq2lulIKL8//n0U1ycVnBHclb3sX5RgawuIjpYu4f4JhyBdFdJazO4qKpv/uV1NTJ9vY2sXFalF2S5jmhoKOo8DWXOzMxIa+spGNiZhUeoaCsjOnplsx2MtHE2X/iF+6RvAL0kuvUs4KVOyjldgHAU0XQU/NAikFpi9rHJ6MKdQUho2pSbFVJNJz/U49uUoVngWTGqG7F0/W3yZPO1+NzgqjkWlKNaulwaOCfj5tJXKIFrOYoWfriRrWf6xqG970wmRV8yMkAgKBkIwA4byomakT/4o934FszXCfLMJllPgSu3PgVmvnhL8KvT8tvDkQlWSLLrVNG5xLBarjNDY7cik18uspCxoVy8Yymp3sdAcD++ePN59pw/AeRYrosdwd4CAAAAABJRU5ErkJggg==', 'base64')
    console.log(imageCode)
    this.ctx.body = imageCode
    //this.success(imageCode)


  }
  async getGeolocationAction () {
    // const secret = this.config('secret');
    const body = this.ctx.request.body;
    // if (!appid || !code) {
    //   return this.fail('接口参数错误');
    // }
    const {latitude, longitude} = JSON.parse(body)
    const url = `http://api.map.baidu.com/geoconv/v1/?coords=${latitude},${longitude}&from=1&to=5&ak=CTGx9tOnzX2k6G9AAj8tu0eWG2vba3ey`;
    return request(url).then(async(body) => {
      const json = JSON.parse(body);
      const {x, y} = json.result[0]
      const url = `http://api.map.baidu.com/geocoder/v2/?location=${x},${y}&output=json&pois=1&ak=CTGx9tOnzX2k6G9AAj8tu0eWG2vba3ey `;
      return request(url).then(async(body) => {
        const json = JSON.parse(body);
        const city = json.result.addressComponent.city
        const model = this.model('xr_city');
        const data = await model.where(`name_cn="${city}"`).find();  
        this.success(data);
      })
    }).catch((error) => {
      if (error) {
        console.warn(error);
        return this.fail(error);
      }
    });
  }
  async goLoginAction () {
    const { mobile, smscode } = this.post();
    console.log(mobile, smscode)
    const result = await this.cache('smscode');
    if (result && result == smscode) {
      const model = this.model('user');
      const user = await model.where(`mobile="${mobile}"`).find();
      if (!think.isEmpty(user)) {
        return this.success(user)
      } else {
        await model.add({ mobile });
        return this.success()
      }
    } else {
      this.fail('短信验证码错误');
    }
  }
  async code2sessionAction() {
    const secret = this.config('secret');
    const { appid, code } = this.post();
    if (!appid || !code) {
      return this.fail('接口参数错误');
    }
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`;
    return request(url).then(async(body) => {
      const json = JSON.parse(body);
      if (json.errcode === 0 || !json.errcode) {
        const { openid, session_key } = json;
        const skey = encryptSha1(session_key);
        // 服务器A拿到session_key后，生成一个随机数我们叫3rd_session,以3rdSessionId为key,以session_key + openid为value
        // 缓存到redis或memcached中；因为微信团队不建议直接将session_key在网络上传输，由开发者自行生成唯一键与session_key关联。其作用是：
        // 将3rdSessionId返回给客户端，维护小程序登录态。
        await this.cache(skey, JSON.stringify({session_key, openid}));
        await this.updateOrAddUserSession_key(openid, skey);
        return this.success({ thirdSession: skey, loginCode: skey });
      } else {
        console.warn(json);
        return this.fail(json.errcode, json.errmsg);
      }
    }).catch((error) => {
      if (error) {
        console.warn(error);
        return this.fail(error);
      }
    });
  }

  async updateOrAddUserSession_key(openid, session_key) {
    const model = this.model('user');
    const user = await model.where(`openid="${openid}"`).find();
    try {
      if (!think.isEmpty(user)) {
        await model.where({openid}).update({ session_key });
      } else {
        await model.add({ openid, session_key });
      }
    } catch (e) {
      return this.fail(e.toString());
    }
  }

  async saveWxUserInfoServerAction() {
    const { userinfo, thirdSession } = this.post();
    const result = await this.cache(thirdSession);
    const {openid} = JSON.parse(result)
    if (!openid) {
      return this.fail(1000, 'openid不存在')
    }
    const model = this.model('user');
    const user = await model.where({openid}).find();
    try {
      if (!think.isEmpty(user)) {
        await model.where({openid}).update(userinfo);
      }
      return this.success();
    } catch (e) {
      console.warn(e);
      return this.fail(1000, e.toString());
    }
  }
  async lovecarAction() {
    var a = {"requestId":"f0c1bc16-8890-4d12-8bb6-ff5d2b6216dd","resultCode":"0000","resultDesc":"success","message":null,"serverTime":"1549876090225","resultData":{"content":[{"type":-1,"imgs":["https://cdn-app.nio.com/NIOAppServer/2019/1/3/69066e45-ee43-490f-9efa-50f630743c1a.png","https://cdn-app.nio.com/NIOAppServer/2019/1/3/f07128dc-1c63-467f-8a09-888f22ac40e8.png"],"titles":["了解和订购ES6","了解和订购ES8"],"links":["nio://intro.vom/page?carSeries=ES6","nio://intro.vom/page?carSeries=ES8"],"params":""},{"type":0,"img":"https://cdn-app.nio.com/NIOAppServer/2018/11/28/25904840-77c4-4eed-bef2-9949a6e7f0c7.jpg","carType":"ES6","priceTitle":"补贴前购买价格","price":"358,000起","discountPriceTitle":"电池租用立减十万","discountPrice":"258,000起","link":"nio://cars.vom/select?carSeries=ES6","linkTitle":"立即配置","params":""},{"type":0,"img":"https://cdn-app.nio.com/NIOAppServer/2018/7/5/4419d75d-e020-4651-b262-e474be5c8373.png","carType":"ES8","priceTitle":"补贴前购买价格","price":"448,000起","discountPriceTitle":"电池租用立减十万","discountPrice":"348,000起","link":"nio://cars.vom/choose","linkTitle":"立即配置","params":""},{"type":1,"img":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/dd214fb9-28a4-42d6-ac57-46841e98ff47.png","title":"担心价格负担重？","desc":"分期贷、智慧贷，随心选择。为您提供最适合的金融方案。","link":"https://vomtools.nio.com/design/financialScheme?show_navigator=false&load_js_bridge=true","params":""},{"type":1,"img":"https://cdn-app.nio.com/NIOAppServer/2018/7/11/dfb75af9-6a20-43fe-b70a-d0a587bca3d7.jpg","title":"有电动车使用焦虑？","desc":"NIO Power全球首创的电能服务体系，让加电比加油更方便。","link":"https://vomtools.nio.com/design/nioPower?show_navigator=false&load_js_bridge=true","params":""},{"type":2,"title":"请了解，很重要","desc":"查看全部","link":"https://app.nio.com/content/500677?load_js_bridge=true&show_navigator=false&content_type=article","params":"","articles":[{"title":"ES6购车指南","desc":"2018-12-15","img":"https://cdn-app.nio.com/user/2018/12/13/a63feaff-2df4-46fb-b75c-739b2393e690.jpg","link":"https://app.nio.com/content/502361?load_js_bridge=true&show_navigator=false&content_type=article","params":""},{"title":"电池租用方案更新","desc":"2018-12-15","img":"https://cdn-app.nio.com/user/2018/12/13/70e5bf27-4a88-485c-92fd-6e3162ef7429.jpg","link":"https://app.nio.com/content/502362?load_js_bridge=true&show_navigator=false&content_type=article","params":""},{"title":"ES8新能源补贴指南","desc":"2018-06-25","img":"https://cdn-app.nio.com/user/2018/7/6/40335e4d-4680-4669-b277-3c9be849f4d0.jpg","link":"https://app.nio.com/content/501197?load_js_bridge=true&show_navigator=false&content_type=article","params":""},{"title":"3分钟看懂蔚来服务","desc":"2018-01-20","img":"https://cdn-app.nio.com/user/2018/3/16/6dee889a-d76d-43b4-993c-a1cdc4ec9540.jpg","link":"https://app.nio.com/content/500705?load_js_bridge=true&show_navigator=false&content_type=article","params":""},{"title":"ES8服务套餐指南-能量无忧","desc":"2018-02-03","img":"https://cdn-app.nio.com/user/2018/3/16/2945e04c-8ae0-4953-8b36-badd8eb94489.jpg","link":"https://app.nio.com/content/500747?load_js_bridge=true&show_navigator=false&content_type=article","params":""},{"title":"ES8服务套餐指南-服务无忧","desc":"2018-02-04","img":"https://cdn-app.nio.com/user/2018/3/16/75605f33-c623-4d43-a92d-93041c2a7e6b.jpg","link":"https://app.nio.com/content/500750?load_js_bridge=true&show_navigator=false&content_type=article","params":""}]},{"type":4,"title":"工具与服务","desc":"助你全方位了解蔚来服务","tools":[{"id":0,"title":"详细配置表","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/842cfe6d-6e52-443c-be02-323b55d2d784.png","link":"nio://intro.vom/carInfo?details=config","params":""},{"id":1,"title":"里程计算器","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/b1b6823d-618b-4f88-b8ec-bb6f86eed367.png","link":"nio://intro.vom/carInfo?details=mileage","params":""},{"id":2,"title":"城市服务查询","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/f785f679-40d2-4adb-bebc-76bda64849ce.png","link":"nio://query.vom/cityService","params":"currentCityName,currentCityCode,orderCityName,orderCityCode"},{"id":3,"title":"一键加电","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/bda72f53-9917-43f1-9e93-66012b28ec64.png","link":"https://ph-help.nio.com:30081/main?no_share=true","params":""},{"id":4,"title":"我的充电桩","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/006a91d1-06ab-494c-acab-f08ffd5c0742.png","link":"nio://service/private_ac_power_charge","params":""},{"id":5,"title":"充电地图","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/c9f38ae1-c981-4643-9105-fcf8cae4428c.png","link":"nio://service/charge_map","params":""}]},{"type":5,"title":"车商城","desc":"为你的爱车锦上添花","tools":[{"id":0,"title":"购买服务","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/3a9acefc-57a2-49ad-a5f7-d4c96c6683ba.png","link":"nio://carmall.nrs/home?tab=0&url=https%3A%2F%2Fm-car-mall.nio.com%2Fmodule_10005%2Fhome%3Fname%3DhomePage%26wv%3Ddo%26tab%3D0","params":""},{"id":1,"title":"购买附件","icon":"https://cdn-app.nio.com/NIOAppServer/2018/7/6/eee0d221-a64c-426b-8d40-a007212ee514.png","link":"nio://carmall.nrs/home?tab=1&url=https%3A%2F%2Fm-car-mall.nio.com%2Fmodule_10005%2Fhome%3Fname%3DhomePage%26wv%3Ddo%26tab%3D1","params":""}]}]}}
    return this.success(a.resultData);
  }
  async weixinSignAction () {
    const body = this.ctx.request.body;
    const res = JSON.parse(body)
    const rawurl = res.url
    console.log(res)
    //测试appid和secret
    const APPID = 'wx8d0a4574dca0be4d'
    const APPSECRET = '9c26606f0acd8c402fe8632f2a13d6d1'
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${APPSECRET}`;
    return request(url).then(async(res) => {
      console.log(res)
      const json = JSON.parse(res);
      const {access_token, expires_in} = json
      const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi`;
      return request(url).then(async(body) => {
        console.log(body)
        const json = JSON.parse(body);
        if (!json.errcode) {
          const { ticket } = json

          // 注意 URL 一定要动态获取，不能 hardcode.
          // $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
          // const url = ;//$url;//"$protocol$_SERVER[HTTP_HOST]:8081/";

          const timestamp = new Date().getTime()
          const nonceStr = createNonceStr();

          // 这里参数的顺序要按照 key 值 ASCII 码升序排序
          const string = `jsapi_ticket=${ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${rawurl}`;
      //echo $string;echo '               111             ';
      //echo  $url;
          const signature = sha1(string);

          const signPackage = {
            appId: APPID,
            nonceStr,
            timestamp,
            url:rawurl,
            signature,
            rawString:string
          }
          this.success(signPackage)
        } else{
          throw new error(json.errmsg)
        }
      })
    }).catch((error) => {
      if (error) {
        console.warn(error);
        return this.fail(error);
      }
    });

    // return this.success({
    //   appId: 'wx98e4306115a33479'.
    //   timestamp: new Date().getTime(),
    //   nonceStr: 'aaa',
    //   signature: 'QfqACUGsrwY57L0QXiFaXqMCDDGvl7UDzFjbX4v2JR1ll8Ss1K0Yo6DEgl3Mw6H5'
    // });
  }
  async getuserInfoAction() {
    const { thirdSession } = this.post();
    if (!thirdSession) {
      return this.fail(1001, '服务端缓存失效');
    }
    const result = await this.cache(thirdSession);
    if (!result) {
      return this.fail(1001, '服务端缓存失效');
    }
    const { openid } = JSON.parse(result)
    if (!openid) {
      return this.fail(1000, 'openid不存在')
    }
    const model = this.model('user');
    const user = await model.where({openid}).find();
    try {
      if (!think.isEmpty(user)) { 
        return this.success(user);
      } else {
        return this.fail(1000, '用户不存在');
      }
    } catch (e) {
      console.warn(e);
      return this.fail(1000, e.toString());
    }
  }
};
